<template>
  <div class="brand-shipment">
    <!-- 1. 标题栏 -->
    <div class="page-header">
      <h2 class="page-title">{{ config.pageTitle }}</h2>
    </div>

    <!-- 2. 金额概览区 -->
    <div class="amount-overview">
      <div 
        class="overview-item" 
        v-for="(item, index) in config.amountOverview" 
        :key="index"
      >
        <span class="label">{{ item.label }}</span>
        <span class="value">{{ amountData[item.key] }}</span>
      </div>
    </div>

    <!-- 3. 筛选区 -->
    <div class="filter-section">
      <div 
        class="filter-row" 
        v-for="(filter, key) in config.filters" 
        :key="key"
      >
        <span class="filter-title">{{ filter.title }}</span>
        <el-checkbox-group 
          v-model="filterModels[key]" 
          @change="(values) => handleFilterGroupChange(key, values)"
          :ref="(el) => filterRefs[key] = el"
        >
          <el-checkbox 
            :label="option" 
            v-for="option in filter.options" 
            :key="option"
          />
        </el-checkbox-group>
        
        <!-- 自定义日期选择器 -->
        <el-date-picker
          v-if="filter.isDatePicker && filterModels[key].includes(filter.datePickerLabel)"
          v-model="customDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="custom-date-picker"
        />
      </div>
    </div>

    <!-- 4. 搜索操作区 -->
    <div class="search-action">
      <div class="shop-id-group">
        <span>{{ config.shopIdLabel }}</span>
        <el-input 
          v-model="shopId" 
          :placeholder="config.shopIdPlaceholder" 
          class="shop-id-input" 
        />
      </div>
      <div class="action-btns">
        <el-button 
          type="primary" 
          class="query-btn" 
          @click="handleQuery"
        >
          {{ config.queryBtnText }}
        </el-button>
        <el-button 
          type="primary" 
          class="export-btn" 
          @click="handleExport"
        >
          {{ config.exportBtnText }}
        </el-button>
      </div>
    </div>

    <!-- 5. 数据表格区（移除固定宽度） -->
    <el-table 
      :data="filteredTableData" 
      border 
      class="data-table"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :row-key="row => row.id"
    >
      <el-table-column type="selection" />
      <el-table-column 
        v-for="column in config.tableColumns" 
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :align="column.align || 'left'"
      >
        <!-- 出货分类标签 -->
        <template #default="scope" v-if="column.prop === 'shipmentType'">
          <el-tag :type="getTagType(scope.row.shipmentType)">
            {{ scope.row.shipmentType }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column 
        :label="config.operationColumn.label"
        align="center"
      >
        <template #default>
          <el-button 
            type="text" 
            class="detail-btn"
          >
            {{ config.operationColumn.text }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 6. 合计区 -->
    <div class="summary-area">
      <div 
        class="summary-item" 
        v-for="(item, index) in config.summaryItems" 
        :key="index"
      >
        <span>{{ item.label }}：</span>
        <el-input 
          v-model="summaryData[item.key]" 
          disabled 
          class="summary-input" 
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, reactive } from 'vue';
import { ElMessage } from 'element-plus';

// 核心配置（移除表格列width属性）
const config = {
  pageTitle: '品牌出货统计',
  shopIdLabel: '店名ID',
  shopIdPlaceholder: '请输入',
  queryBtnText: '查询',
  exportBtnText: '导出',
  
  // 金额概览配置
  amountOverview: [
    { label: '当前总出货', key: 'totalShipmentAmount' },
    { label: '品牌A', key: 'brandAAmount' },
    { label: '品牌B', key: 'brandBAmount' },
    { label: '品牌C', key: 'brandCAmount' }
  ],
  
  // 筛选器配置
  filters: {
    brand: {
      title: '品牌分类',
      options: ['全部', '蓝妮尔', '贝亦美', '和悦肽'],
      allLabel: '全部',
      isDatePicker: false
    },
    productType: {
      title: '产品类型',
      options: ['全部', '单品', '套盒', '其它'],
      allLabel: '全部',
      isDatePicker: false
    },
    shipment: {
      title: '出货统计',
      options: ['全部', '正价', '秒杀', '特价', '赠送', '员工'],
      allLabel: '全部',
      isDatePicker: false
    },
    date: {
      title: '订单日期',
      options: ['不限', '今天', '最近3天', '最近7天', '本月', '自定义时间段'],
      allLabel: '不限',
      isDatePicker: true,
      datePickerLabel: '自定义时间段'
    }
  },
  
  // 表格列配置（移除width属性）
  tableColumns: [
    { prop: 'serial', label: '序号', align: 'center' },
    { prop: 'productName', label: '产品名称' },
    { prop: 'productCode', label: '产品编号' },
    { prop: 'brand', label: '品牌分类', align: 'center' },
    { prop: 'productType', label: '产品类型', align: 'center' },
    { 
      prop: 'shipmentType', 
      label: '出货分类', 
      align: 'center'
    },
    { prop: 'quantity', label: '数量', align: 'center' },
    { prop: 'retailPrice', label: '零售价', align: 'right' },
    { prop: 'discountPrice', label: '折扣价', align: 'right' },
    { prop: 'shipmentAmount', label: '出货金额', align: 'right' },
    { prop: 'retailTotal', label: '零售价总额', align: 'right' },
    { prop: 'brandManager', label: '品牌经理' },
    { prop: 'beautician', label: '美容导师' }
  ],
  
  // 操作列配置（移除width属性）
  operationColumn: {
    label: '出货明细',
    text: '明细'
  },
  
  // 合计区配置
  summaryItems: [
    { label: '合计', key: 'totalAmount' },
    { label: '零售总价', key: 'retailTotalPrice' }
  ]
};

// 金额数据
const amountData = reactive({
  totalShipmentAmount: '¥40000.00',
  brandAAmount: '¥20000.00',
  brandBAmount: '¥10000.90',
  brandCAmount: '¥2000.60'
});

// 合计区数据
const summaryData = reactive({
  totalAmount: '¥40000.00',
  retailTotalPrice: '¥59800.00'
});

// 筛选器相关
const filterModels = reactive({
  brand: [],
  productType: [],
  shipment: [],
  date: []
});
const filterRefs = ref({});
const customDateRange = ref([]);
const shopId = ref('');

// 表格数据
const tableData = ref([]);
const filteredTableData = ref([]);
const selectedRows = ref([]);

// 初始化
onMounted(() => {
  initTableData();
});

// 初始化表格数据
const initTableData = () => {
  tableData.value = [
    {
      id: '1',
      serial: 1,
      productName: '活性肽面膜',
      productCode: 'MCC5649',
      brand: '蓝妮尔',
      productType: '单品',
      shipmentType: '正价',
      quantity: 151,
      retailPrice: '¥190.00',
      discountPrice: '¥180.00',
      shipmentAmount: '¥180.00',
      retailTotal: '¥19890.00',
      brandManager: '金金老师',
      beautician: '李三燕'
    },
    {
      id: '2',
      serial: 2,
      productName: '焕颜精华套盒',
      productCode: 'MCC5650',
      brand: '贝亦美',
      productType: '套盒',
      shipmentType: '秒杀',
      quantity: 89,
      retailPrice: '¥290.00',
      discountPrice: '¥250.00',
      shipmentAmount: '¥250.00',
      retailTotal: '¥25810.00',
      brandManager: '金金老师',
      beautician: '李三燕'
    },
    {
      id: '3',
      serial: 3,
      productName: '舒缓面霜',
      productCode: 'MCC5651',
      brand: '和悦肽',
      productType: '单品',
      shipmentType: '特价',
      quantity: 45,
      retailPrice: '¥390.00',
      discountPrice: '¥320.00',
      shipmentAmount: '¥320.00',
      retailTotal: '¥17550.00',
      brandManager: '王老师',
      beautician: '张海燕'
    }
  ];
  filteredTableData.value = [...tableData.value];
};

// 筛选组变化处理
const handleFilterGroupChange = (groupKey, values) => {
  const filter = config.filters[groupKey];
  const allLabel = filter.allLabel;
  const options = filter.options.filter(option => option !== allLabel);
  
  if (values.includes(allLabel)) {
    if (values.length === 1) {
      filterModels[groupKey] = [...options];
      nextTick(() => {
        filterRefs[groupKey]?.setCheckedValues(options);
      });
    } else if (values.length === options.length + 1) {
      filterModels[groupKey] = [];
      nextTick(() => {
        filterRefs[groupKey]?.setCheckedValues([]);
      });
    }
  } else if (values.length === options.length) {
    filterModels[groupKey] = [...options, allLabel];
    nextTick(() => {
      filterRefs[groupKey]?.setCheckedValues([...options, allLabel]);
    });
  }

  handleFilter();
};

// 通用筛选逻辑
const handleFilter = () => {
  let result = [...tableData.value];

  if (filterModels.brand.length > 0) {
    result = result.filter(item => filterModels.brand.includes(item.brand));
  }
  if (filterModels.productType.length > 0) {
    result = result.filter(item => filterModels.productType.includes(item.productType));
  }
  if (filterModels.shipment.length > 0) {
    result = result.filter(item => filterModels.shipment.includes(item.shipmentType));
  }
  if (shopId.value) {
    result = result.filter(item => item.shopId?.includes(shopId.value));
  }

  filteredTableData.value = result;
};

// 出货分类标签类型
const getTagType = (type) => {
  switch (type) {
    case '正价': return 'success';
    case '秒杀': return 'danger';
    case '员工': return 'primary';
    case '赠送': return 'info';
    case '特价': return 'warning';
    default: return '';
  }
};

// 其他功能方法
const handleQuery = () => {
  handleFilter();
  ElMessage.success('查询成功');
};

const handleExport = () => {
  if (filteredTableData.value.length === 0) {
    ElMessage.warning('无数据可导出');
    return;
  }
  ElMessage.success('导出成功');
};

const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};
</script>

<style scoped>
/* 金额概览区 */
.amount-overview {
  display: flex;
  align-items: center;
  gap: 60px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}
.overview-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
}
.overview-item .label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}
.overview-item .value {
  font-size: 30px;
  color: #23c6c8;
  font-weight: 600;
  cursor: pointer;
}

/* 筛选区样式 */
.filter-section {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}
.filter-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}
.filter-title {
  width: 80px;
  text-align: right;
  font-size: 14px;
  color: #333;
}
.el-checkbox-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}
.custom-date-picker {
  margin-left: 90px;
  width: calc(100% - 90px);
  margin-top: 8px;
}

/* 搜索操作区 */
.search-action {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
  width: 100%;
}
.shop-id-group {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: auto;
}
.shop-id-input {
  width: 200px;
}
.action-btns {
  display: flex;
  gap: 10px;
}

/* 表格样式（不设置固定宽度，由内容自动撑开） */
.data-table {
  margin-bottom: 20px;
  table-layout: auto; /* 自动表格布局，列宽由内容决定 */
}

/* 合计区 */
.summary-area {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}
.summary-input {
  width: 150px;
  text-align: right;
}

/* 基础样式 */
.brand-shipment {
  padding: 20px;
  background: #fff;
  font-family: "Microsoft Yahei", sans-serif;
}
</style>